package com.aduerr.v1shouyin.unioncard;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.DatabaseManager;
import com.aduerr.v1shouyin.entity.OrderRecordEntity;
import com.yeahka.shouyintong.sdk.info.TradeInfo;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.suzp1984.jbig.JbigCodec;
import io.github.suzp1984.jbig.JbigCodecFactory;

/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2019/7/15 11:30
 * @change
 * @chang 2020/02/28
 * @class 乐刷换了sdk，这个Activity没用了
 */

public class UnionSignActivity extends BaseUnionActivity {


    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_transaction_type)
    TextView tvTransactionType;
    @BindView(R.id.paint_content)
    FrameLayout paintContent;
    @BindView(R.id.bt_confirm)
    Button btComfirm;
    @BindView(R.id.image_view_01)
    ImageView imageView;

    int type; //1:消费，2：退款
    private Bitmap cacheBitMap;
    private TradeInfo tradeInfo;
    private PaintView mPaintView;

    //使用Bitmap加Matrix来缩放
    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_union_sign;
    }

    @Override
    protected void initBase() {
        super.initBase();
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 0);
        tvTitle.setText("电子签名");
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("跳过");
        OrderRecordEntity order = new OrderRecordEntity();
        if(type == 1) {
            tvTransactionType.setText("交易成功");
            order.setType(5);
        } else if(type == 2) {
            tvTransactionType.setText("退款成功");
            order.setType(12);
        }
        tradeInfo = ((TradeInfo) getIntent().getParcelableExtra("tradeInfo"));
        order.setReferNo(tradeInfo.getReferenceNo());
        DatabaseManager.getInstance().insert(order);//插入记录

        btComfirm.setEnabled(false);
        mPaintView = new PaintView(this);
        AbsListView.LayoutParams params =
                new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
        mPaintView.setLayoutParams(params);
        mPaintView.requestFocus();
        mPaintView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP) {
                    btComfirm.setEnabled(true);
                }

                return false;
            }
        });
        paintContent.addView(mPaintView);
    }

    public void reset() {
        mPaintView.setVisibility(View.VISIBLE);
        btComfirm.setEnabled(false);
    }

    private boolean confirm() {
        Bitmap cachebBitmap = mPaintView.getCachebBitmap();
        cacheBitMap = resizeImage(cachebBitmap, cachebBitmap.getWidth() / 2,
                cachebBitmap.getHeight() / 2);
//        tradeInfo.setSignName(cacheBitMap);
        return true;
    }

    @OnClick({R.id.img_back, R.id.tv_reset, R.id.bt_confirm, R.id.tv_right})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                new AlertDialog.Builder(UnionSignActivity.this,
                        R.style.Theme_AppCompat_DayNight_Dialog_Alert)
                        .setTitle("提示")
                        .setMessage("退出将无法打印小票，确定退出？")
                        .setCancelable(false)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        finish();
                                    }
                                })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .show();
                break;
            case R.id.tv_reset:
                reset();
                mPaintView.clear();
                btComfirm.setEnabled(false);
                break;
            case R.id.bt_confirm:
                onConfirmClick();
                break;
            case R.id.tv_right:
                print(true);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(UnionSignActivity.this,
                R.style.Theme_AppCompat_DayNight_Dialog_Alert)
                .setTitle("提示")
                .setMessage("退出将无法打印小票，确定退出？")
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                UnionSignActivity.super.onBackPressed();
                            }
                        })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
    }

    private void uploadSign() {
        Bitmap bitmap = getSignBitmap();

        //byte[] bytes = BitmapUtil.bitmapToBytesWithNoChagneJPEG(bitmap);
        Bitmap[] bitmaps = new Bitmap[1];
        bitmaps[0] = bitmap;

        JbigCodec jbigCodec =
                JbigCodecFactory.getJbigCodec(JbigCodecFactory.CODEC.JNI_CODEC);

        /*if(jbigCodec != null) {
            byte[] jbigData = jbigCodec.encode(bitmaps);
            posService.uploadSign(tradeInfo, jbigData).observeOn(AndroidSchedulers.mainThread()).subscribe(new CustomSingleObserver<Response>(this, "正在上传奇签名...") {
                @Override
                public void onSuccess(Response response) {
                    String responseCode = response.getCode();
                    if(TextUtils.equals("00", responseCode)) {
//                        showToast("签名上送成功");
                        if(PosDeviceFactory.getPosDevice(UnionSignActivity.this).isSupportPrint()) {
                            print(true);
                        }
//                        finish();
                    } else {
                        showToast(PosDeviceFactory.getResponseByCode(String.format("%s" +
                                        "(%s)",
                                PosDeviceFactory.getResponseByCode(responseCode),
                                responseCode)));
                    }
                    super.onSuccess(response);
                }
            });
        } else {
            showToast("生成签名图片错误，请重试");
            reset();
        }*/

    }


    private void onConfirmClick() {
        try {
            if(confirm()) {
                uploadSign();
            }
        } catch(Exception e) {
            e.printStackTrace();
            showToast("请重试");
        }
    }


    public Bitmap getSignBitmap() {
        return resizeImage(cacheBitMap, 237, 79);
    }

    private void print(boolean isFirst) {
       /* if(PosDeviceFactory.isSupportDevice()) {
            final IDevice posDevice = PosDeviceFactory.getPosDevice(this);
            posDevice.getPrinter().observeOn(AndroidSchedulers.mainThread()).subscribe(new CustomSingleObserver<IPrinter>(this) {
                @Override
                public void onSuccess(IPrinter printer) {
                    printCardTrade(posDevice, printer, tradeInfo, isFirst);
//                    Log.i("订单号", "订单号" + tradeInfo.getOrderId());
                }

                @Override
                public void handlerError(Throwable e) {
                    super.handlerError(e);

                }
            });
        } else {
        }*/
    }

  /*  void printCardTrade(IDevice posDevice, IPrinter printer, TradeInfo tradeInfo,
                        boolean isFirst) {
        PrinterWrapper.printUnionOrder(BitmapFactory.decodeResource(getResources(),
                R.drawable.print_union), posDevice, printer, tradeInfo)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new PrintObserver(this) {
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        if(isFirst) {
                            new AlertDialog.Builder(UnionSignActivity.this,
                                    R.style.Theme_AppCompat_DayNight_Dialog_Alert)
                                    .setTitle("提示")
                                    .setMessage("请撕下票据打印下一联")
                                    .setCancelable(false)
                                    .setPositiveButton("确定",
                                            new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog,
                                                            int which) {
                                            print(false);
                                        }
                                    })
                                    .show();
                        } else {
                            Intent intent = new Intent(UnionSignActivity.this,
                                    UnionCompleteActivity.class);
                            intent.putExtra("type", type);
                            startActivity(intent);
                            finish();
                        }
                    }
                });
    }*/


}
